import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/28 20:50
 * @description 自定义排序 使用Map
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] votes = {"ABC", "ACB", "ABC", "ACB", "ACB"};
        solution.rankTeams(votes);
    }
    public String rankTeams(String[] votes) {
        int n = votes.length;
        if (n == 1) {
            return votes[0];
        }
        // key - 队名，value - 每个排名获得的票数
        Map<Character, int[]> map = new HashMap<>();

        for (String vote : votes) {
            for (int i = 0; i < vote.length(); i++) {
                int[] rank = map.getOrDefault(vote.charAt(i), new int[26]);
                rank[i]++;
                map.put(vote.charAt(i), rank);
            }
        }

        List<Map.Entry<Character, int[]>> list = new ArrayList<>(map.entrySet());

        Collections.sort(list, (t1 , t2) -> {
            int[] rank1 = t1.getValue();
            int[] rank2 = t2.getValue();
            // 根据投票降序排序
            for (int i = 0; i < 26; i++) {
                if (rank1[i] != rank2[i]) {
                    return rank2[i] - rank1[i];
                }
            }
            // 按字母升序
            return t1.getKey() - t2.getKey();
        });

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<Character, int[]> entry : list) {
            sb.append(entry.getKey());
        }
        return sb.toString();
    }
}
